package com.yunxi.service.dubboService.impl.sat;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.util.StringUtil;
import com.yunxi.baseDataToHub.pojo.urm.FollowInformationVO;
import com.yunxi.baseDataToHub.service.urm.UrmDubboService;
import com.yunxi.core.page.PageHelperPlus;
import com.yunxi.core.web.ApiResult;
import com.yunxi.core.web.DictConstant;
import com.yunxi.core.web.LoginInfo;
import com.yunxi.dealer.pojo.PartnerVO;
import com.yunxi.model.order.OrderCustomer;
import com.yunxi.model.sat.*;
import com.yunxi.sat.pojo.*;
import com.yunxi.sat.service.SatCustomerFollowDubboService;
import com.yunxi.service.localService.OrderCustomerService;
import com.yunxi.service.localService.sat.*;
import com.yunxi.sys.pojo.StaffVO;
import com.yunxi.sys.service.StaffDubboService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import java.lang.reflect.InvocationTargetException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 客户跟进记录表 服务实现类
 * </p>
 *
 * @author caoYong
 * @since 2019-07-11
 */
public class SatCustomerFollowDubboServiceImpl implements SatCustomerFollowDubboService {

    private static final Logger logger = LoggerFactory.getLogger(SatCustomerFollowDubboServiceImpl.class);

    @Autowired
    @Qualifier(value = "satCustomerFollowServiceImpl")
    SatCustomerFollowService satCustomerFollowService;

    @Autowired
    @Qualifier(value = "satConfigServiceImpl")
    SatConfigService satConfigService;

    @Autowired
    @Qualifier(value = "satLostApplyServiceImpl")
    SatLostApplyService satLostApplyService;

    @Autowired
    @Qualifier(value = "orderCustomerServiceImpl")
    OrderCustomerService orderCustomerService;

    @Autowired
    @Qualifier(value = "handleVehicleServiceImpl")
    HandleVehicleService handleVehicleService;

    @Autowired
    UrmDubboService urmDubboServiceImplBiz;

    @Autowired
    @Qualifier(value = "staffDubboServiceBiz")
    StaffDubboService staffDubboService;

    @Autowired
    @Qualifier(value = "satCustomerClueServiceImpl")
    SatCustomerClueService satCustomerClueService;

    @Autowired
    @Qualifier(value = "msgTemplateServiceImpl")
    MsgTemplateService msgTemplateService;

    @Autowired
    @Qualifier(value = "satMessServiceImpl")
    SatMessService satMessService;

    @Override
    public SatCustomerFollowVO getById(String id) throws Exception {
        SatCustomerFollow satCustomerFollow = satCustomerFollowService.getById(id);
        if(satCustomerFollow != null){
            SatCustomerFollowVO satCustomerFollowVO = new SatCustomerFollowVO();
            BeanUtils.copyProperties(satCustomerFollow, satCustomerFollowVO);
            return satCustomerFollowVO;
        }
        else{
            throw new Exception("操作失败,无法根据id:"+id+"找到对应跟进记录!");
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public ApiResult saveOrUpdate(SatCustomerFollowVO satCustomerFollowVO,LoginInfo loginInfo) throws Exception {
        if(StringUtils.isEmpty(loginInfo.getPartnerCode()))throw new Exception("操作失败,请选择渠道商人员账号新增跟进!");
        setPartnerCode(satCustomerFollowVO, loginInfo);
        String customerNo = satCustomerFollowVO.getCustomerNo();
        satCustomerFollowVO.setCreateBy(loginInfo.getUserCode());
        //获取当前跟进客户的客户级别
        String oldLevel = satCustomerFollowService.getCustomerLevelByNo(satCustomerFollowVO);
        //获取跟进意向级别
        String level = satCustomerFollowVO.getNewCustlevel();
        if (StringUtils.isEmpty(level)) throw new Exception("操作失败,新意向级别为空!");
        SatCustomerFollow satCustomerFollow = new SatCustomerFollow();
        BeanUtils.copyProperties(satCustomerFollowVO, satCustomerFollow);
        //1.生成一条已跟进的跟进记录
        satCustomerFollow.setFollowStatus(1);
        satCustomerFollow.setCompleteFollowTime(new Date());
        satCustomerFollowVO.setCompleteFollowTime(new Date());
        satCustomerFollowVO.setFollowStatus(1);
        satCustomerFollow.setLevel(oldLevel);
        //2.如果没有选择下次跟进日期,则根据级别计算出下次跟进日期.
        //选择了下次跟进日期,则需要判断日期是否在级别限定日期范围内
        checkPlanFollowDate(satCustomerFollow);
        //3.如果选择了计划跟进事项,则根据跟进级别/计划跟进时间,生成一条待跟进的记录
        if(StringUtil.isNotEmpty(satCustomerFollow.getPlanFollowItem())){
            addCustomerFollow(loginInfo, level, satCustomerFollow);
        }
        //5.更新客户级别
        if(StringUtil.isNotEmpty(customerNo)){
            satCustomerFollowService.updateCustomerLevel(satCustomerFollowVO);
        }
        // 判断用户是否有交车记录 有则设置为老用户跟进
        QueryWrapper<HandleVehicle> queryWrapper = new QueryWrapper<HandleVehicle>();
        queryWrapper.eq("CUSTOMER_NO",satCustomerFollowVO.getCustomerNo());
        queryWrapper.eq("HANDLE_STATUS",2);
        queryWrapper.eq("PARTNER_CODE",loginInfo.getPartnerCode());
        int recordCount = handleVehicleService.count(queryWrapper);
        if(recordCount>0){
            satCustomerFollow.setIsOldCustomerFollow(1);
        }
        satCustomerFollowService.saveOrUpdate(satCustomerFollow);

        //设置URM客户跟进字段
        FollowInformationVO followInformationVO = setFollowInforURM(satCustomerFollowVO);
        //发送客户跟进信息到URM
        return sendFollowInfo2URM(followInformationVO);
    }

    private ApiResult sendFollowInfo2URM(FollowInformationVO followInformationVO) throws Exception {
        ApiResult apiResult = null;
        try {
            apiResult = urmDubboServiceImplBiz.sendFollowInformationPMS2Urm(followInformationVO);
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            e.printStackTrace();
        }
        if (200 != apiResult.getCode()) {
            logger.error("URM接口执行，同步客户跟进信息失败，事务回滚!");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new Exception( "URM接口执行，同步客户跟进信息失败");
        }
        if (apiResult.getData()!=null ){
            JSON.parseObject((String) apiResult.getData());
        }
        return apiResult;
    }

    private FollowInformationVO setFollowInforURM(SatCustomerFollowVO satCustomerFollowVO) {
        FollowInformationVO followInformationVO = new FollowInformationVO();
        followInformationVO.setCustomerNo(satCustomerFollowVO.getCustomerNo());//客户ID
        followInformationVO.setParnterNo(satCustomerFollowVO.getPartnerCode());//渠道商代码
        followInformationVO.setUserid(satCustomerFollowVO.getCreateBy());//销售顾问
        followInformationVO.setTouchRegard(satCustomerFollowService.queryDictCn("Customer_FollowItem",satCustomerFollowVO.getFollowItem()));//接触事项
        followInformationVO.setResult(satCustomerFollowVO.getFollowReasult());//跟进描述
        followInformationVO.setTouchCount(satCustomerFollowVO.getFollowCount());//跟进次数
        followInformationVO.setIsDriver(satCustomerFollowVO.getIsDriver());//是否试驾
        followInformationVO.setNoDriverCause(satCustomerFollowVO.getNoDriverCause());//未试驾原因
        if(satCustomerFollowVO.getFollowStatus() != null){
            followInformationVO.setFollowState(satCustomerFollowVO.getFollowStatus().toString());//跟进、回访及ITMC跟踪状态
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = simpleDateFormat.format(new Date());
        followInformationVO.setCreateTime(format);//创建时间
        followInformationVO.setTouchModel(satCustomerFollowService.queryDictCn("Customer_FollowStyle",satCustomerFollowVO.getFollowStyle()));//接触方式
        followInformationVO.setFactTouchItem(satCustomerFollowVO.getFactTouchItem());//到店事项及发生动作
//        followInformationVO.setPlanTouchTime(satCustomerFollowService.queryDictCn("Customer_FollowItem",satCustomerFollowVO.getPlanFollowItem()));//计划跟进事件
        if(satCustomerFollowVO.getPlanFollowTime() != null){
            Date planFollowTime = satCustomerFollowVO.getPlanFollowTime();
            SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String format1 = simpleDateFormat1.format(planFollowTime);
            followInformationVO.setPlanTouchTime(format1);//计划接触时间
        }
        Date completeFollowTime = satCustomerFollowVO.getCompleteFollowTime();
        if(completeFollowTime != null){
            String format1 = simpleDateFormat.format(completeFollowTime);
            followInformationVO.setFactTouchTime(format1);//实际接触时间
        }
        followInformationVO.setAwayTime(satCustomerFollowVO.getAwayTime());//迁移数据实际接触时间
        followInformationVO.setPlanTouchModel(satCustomerFollowService.queryDictCn("Customer_FollowStyle",satCustomerFollowVO.getPlanFollowStyle()));//计划接触方式
        followInformationVO.setIsUpdate(format);//更新时间
        followInformationVO.setForecastrItem(satCustomerFollowVO.getForecastrItem());//预计来店动作
        followInformationVO.setNewrCustlevel(satCustomerFollowService.queryDictCn("Customer_IntentionLevel",satCustomerFollowVO.getNewCustlevel()));//新意向级别
        return followInformationVO;
    }

    @Override
    public void addFollow(SatCustomerFollowVO satCustomerFollowVO, LoginInfo loginInfo) throws Exception {
        if(StringUtils.isEmpty(loginInfo.getPartnerCode()))throw new Exception("操作失败,请选择渠道商人员账号新增跟进!");
        setPartnerCode(satCustomerFollowVO, loginInfo);
        String oldLevel = satCustomerFollowService.getCustomerLevelByNo(satCustomerFollowVO);
        SatCustomerFollow satCustomerFollow = new SatCustomerFollow();
        BeanUtils.copyProperties(satCustomerFollowVO, satCustomerFollow);
        //1.生成一条待跟进的跟进记录
        satCustomerFollow.setFollowStatus(0);
        satCustomerFollow.setLevel(oldLevel);
        //2.如果没有选择下次跟进日期,则根据级别计算出下次跟进日期.
        //选择了下次跟进日期,则需要判断日期是否在级别限定日期范围内
        checkPlanFollowDate(satCustomerFollow);
        // 判断用户是否有交车记录 有则设置为老用户跟进
        QueryWrapper<HandleVehicle> queryWrapper = new QueryWrapper<HandleVehicle>();
        queryWrapper.eq("CUSTOMER_NO",satCustomerFollowVO.getCustomerNo());
        queryWrapper.eq("HANDLE_STATUS",2);
        queryWrapper.eq("PARTNER_CODE",loginInfo.getPartnerCode());
        int recordCount = handleVehicleService.count(queryWrapper);
        if(recordCount>0){
            satCustomerFollow.setIsOldCustomerFollow(1);
        }
        satCustomerFollowService.saveOrUpdate(satCustomerFollow);
    }


    /**
     * 跟进完成
     * @param satCustomerFollowVO
     * @param loginInfo
     * @throws Exception
     */
    @Override
    public void complete(SatCustomerFollowVO satCustomerFollowVO, LoginInfo loginInfo) throws Exception {
        String followId = satCustomerFollowVO.getFollowId();
        String level = satCustomerFollowVO.getNewCustlevel();
        if (StringUtils.isEmpty(level)) throw new Exception("操作失败,新意向级别为空!");
        String customerNo = satCustomerFollowVO.getCustomerNo();
        String lostReason = satCustomerFollowVO.getLostReason();
        satCustomerFollowVO.setPartnerCode(loginInfo.getPartnerCode());
        if(StringUtil.isNotEmpty(followId)){
            String oldLevel = satCustomerFollowService.getCustomerLevelByNo(satCustomerFollowVO);
            SatCustomerFollow satCustomerFollow = new SatCustomerFollow();
            BeanUtils.copyProperties(satCustomerFollowVO, satCustomerFollow);
            satCustomerFollow.setFollowStatus(1);
            satCustomerFollow.setCompleteFollowTime(new Date());
            satCustomerFollow.setLevel(oldLevel);
            //1.校验计划跟进日期
            checkPlanFollowDate(satCustomerFollow);
            //2.更新跟进单状态为完成
            satCustomerFollowService.saveOrUpdate(satCustomerFollow);
            //3.如果选择了计划跟进事项,则根据跟进级别/计划跟进时间,生成一条待跟进的记录
            if(StringUtil.isNotEmpty(satCustomerFollow.getPlanFollowItem())){
                // 判断用户是否有交车记录 有则设置为老用户跟进
                QueryWrapper<HandleVehicle> queryWrapper = new QueryWrapper<HandleVehicle>();
                queryWrapper.eq("CUSTOMER_NO",satCustomerFollowVO.getCustomerNo());
                queryWrapper.eq("HANDLE_STATUS",2);
                int recordCount = handleVehicleService.count(queryWrapper);
                if(recordCount>0){
                    satCustomerFollow.setIsOldCustomerFollow(1);
                }
                addCustomerFollow(loginInfo, level, satCustomerFollow);
            }
            //4.如果战败原因不为空,则生成一条战败申请
            if(StringUtil.isNotEmpty(lostReason)){
                addLostApply(satCustomerFollow,loginInfo);
            }
            //5.如果跟进后级别不为战败,更新客户级别
//            if(StringUtil.isNotEmpty(level) && !level.equals("7") && StringUtil.isNotEmpty(customerNo)){
                satCustomerFollowService.updateCustomerLevel(satCustomerFollowVO);
//            }
        }
        else{
            throw new Exception("操作失败,主键id为空!");
        }
    }

    /**
     * 新增一条客户跟进
     * @param loginInfo
     * @param level
     * @param satCustomerFollow
     */
    private void addCustomerFollow(LoginInfo loginInfo, String level, SatCustomerFollow satCustomerFollow) {
        //一个客户只能有一条待跟进,新增待跟进时,检查是否已存在待跟进记录,存在即删除 20190902增加的逻辑
        QueryWrapper<SatCustomerFollow> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("CUSTOMER_NO",satCustomerFollow.getCustomerNo());
        queryWrapper1.eq("PARTNER_CODE",loginInfo.getPartnerCode());
        queryWrapper1.eq("FOLLOW_STATUS",0);
        satCustomerFollowService.remove(queryWrapper1);
        //===========
        SatCustomerFollow satCustomerFollow1 = new SatCustomerFollow();
        satCustomerFollow1.setCustomerNo(satCustomerFollow.getCustomerNo());
        satCustomerFollow1.setPartnerCode(satCustomerFollow.getPartnerCode());
        satCustomerFollow1.setFollowStatus(0);
        satCustomerFollow1.setPartnerCode(loginInfo.getPartnerCode());
        satCustomerFollow1.setCreateBy(loginInfo.getUserCode());
        satCustomerFollow1.setIsOldCustomerFollow(satCustomerFollow.getIsOldCustomerFollow());
        satCustomerFollow1.setFollowItem(satCustomerFollow.getPlanFollowItem());
        satCustomerFollow1.setFollowStyle(satCustomerFollow.getPlanFollowStyle());
        //如果下次计划跟进时间不为空,则作为待跟进记录的计划跟进时间
        if(satCustomerFollow.getPlanFollowTime() != null){
            satCustomerFollow1.setPlanFollowTime(satCustomerFollow.getPlanFollowTime());
        }
        //为空,则根据级别,去销售助手配置表查询客户级别对应跟进天数,当前日期加上级别对应跟进天数,即为下次跟进日期
        else{
            if(StringUtil.isNotEmpty(level)){
                QueryWrapper<SatConfig> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("PARTNER_CODE",satCustomerFollow.getPartnerCode());
                SatConfig one = satConfigService.getOne(queryWrapper);
                Integer followDays = null;
                if(one != null){
                    switch (level) {
                        case "2":
                            followDays = one.getCustomerHFollowDays();
                            break;
                        case "3":
                            followDays = one.getCustomerAFollowDays();
                            break;
                        case "4":
                            followDays = one.getCustomerBFollowDays();
                            break;
                        case "5":
                            followDays = one.getCustomerCFollowDays();
                            break;
                        case "6":
                            followDays = one.getCustomerOtherFollowDays();
                            break;
                    }
                }
                if(followDays != null){
                    Date date = new Date();
                    Calendar calendar = Calendar.getInstance();
                    calendar.add(Calendar.DATE,followDays);
                    date = calendar.getTime();
                    satCustomerFollow1.setPlanFollowTime(date);
                }
                else{
                    satCustomerFollow1.setPlanFollowTime(new Date());
                }
            }
            else {
                satCustomerFollow1.setPlanFollowTime(new Date());
            }
        }
        satCustomerFollow1.setCreateTime(new Date(new Date().getTime()+1000));
        satCustomerFollowService.saveOrUpdate(satCustomerFollow1);
    }

    /**
     * 新增战败申请
     * @param satCustomerFollow
     */
    private void addLostApply(SatCustomerFollow satCustomerFollow,LoginInfo loginInfo) throws InvocationTargetException, IllegalAccessException {
        SatLostApply satLostApply = new SatLostApply();
        satLostApply.setFollowId(satCustomerFollow.getFollowId());
        satLostApply.setPartnerCode(satCustomerFollow.getPartnerCode());
        //根据客户编号,当前登录人获取最新一条被领取的线索
        SatCustomerClueVO customerClueInfo = satCustomerFollowService.getCustomerClueInfo(satCustomerFollow);
        if(customerClueInfo != null){
            satLostApply.setClueId(customerClueInfo.getClueId());
        }
        satLostApply.setApplyOrderStatus(1);//战败待审批
        satLostApply.setApplyTime(new Date());
        satLostApply.setCreateBy(loginInfo.getUserCode());
        satLostApply.setApplyUser(loginInfo.getUserCode());
        satLostApply.setCustomerNo(satCustomerFollow.getCustomerNo());
        QueryWrapper<SatLostApply> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("CUSTOMER_NO",satLostApply.getCustomerNo());
        queryWrapper.eq("PARTNER_CODE",satLostApply.getPartnerCode());
        List<SatLostApply> list = satLostApplyService.list(queryWrapper);
        if(list != null && list.size() > 0){
            satLostApply.setApplyCount(list.size()+1);
        }
        satLostApplyService.saveOrUpdate(satLostApply);

        //2.生成消息给该渠道商下所有销售经理
        pushMsg(satCustomerFollow, loginInfo.getRoleCode(),satLostApply.getApplyId());
    }



    @Override
    public void removeById(String id) {
        satCustomerFollowService.removeById(id);
    }

    @Override
    public PageInfo<SatCustomerFollowVO> findPageByVO(SatCustomerFollowVO satCustomerFollowVO, Integer pageNum, Integer pageSize, LoginInfo loginInfo) throws Exception {
        setPartnerCode(satCustomerFollowVO, loginInfo);
        PageInfo<SatCustomerFollowVO> pageInfo = satCustomerFollowService.pageByVo(satCustomerFollowVO, pageNum, pageSize);
        return pageInfo;
    }



    @Override
    public void removeByListVo(List<SatCustomerFollowVO> satCustomerFollowVOList) throws Exception {
        satCustomerFollowService.removeByListVo(satCustomerFollowVOList);
    }

    @Override
    public List listByVo(SatCustomerFollowVO satCustomerFollowVO) {
        return satCustomerFollowService.listByVo(satCustomerFollowVO);
    }

    @Override
    public void del(List<String> list,String updateBy) throws Exception {
        if(list != null){
            for (String id : list){
                SatCustomerFollow byId = satCustomerFollowService.getById(id);
                if(byId != null){
                    byId.setIsDel(1);
                    byId.setUpdateBy(updateBy);
                    satCustomerFollowService.updateById(byId);
                }
                else{
                    throw new Exception("操作失败,无法根据id:"+id+"找到对应跟进记录!");
                }
            }
        }
        else{
            throw new Exception("操作失败,list为空!");
        }
    }

    /**
     * 根据客户编号查询跟进信息
     * @param customerNo
     * @param loginInfo
     * @return
     * @throws Exception
     */
    @Override
    public List<SatCustomerFollowVO> getFollowsByNo(String customerNo, LoginInfo loginInfo) throws Exception {
        return queryFollows(customerNo, loginInfo,1);
    }

    @Override
    public PageInfo<SatCustomerFollowVO> getFollowsByNoForPage(String customerNo, LoginInfo loginInfo,Integer pageNum,Integer pageSize) throws Exception {
        PageHelperPlus.startPage(pageNum,pageSize);
        List<SatCustomerFollowVO> list = queryFollows(customerNo, loginInfo, 1);
        PageInfo<SatCustomerFollowVO> pageInfo = new PageInfo(list);
        return pageInfo;
    }

    /**
     * 根据客户编号查询待跟进信息
     * @param customerNo
     * @param loginInfo
     * @return
     * @throws Exception
     */
    @Override
    public List<SatCustomerFollowVO> getWaitFollowsByNo(String customerNo, LoginInfo loginInfo) throws Exception {
        return queryFollows(customerNo, loginInfo,0);
    }

    private List<SatCustomerFollowVO> queryFollows(String customerNo, LoginInfo loginInfo,Integer followStatus) throws Exception {
        SatCustomerFollowVO satCustomerFollowVO = new SatCustomerFollowVO();
        satCustomerFollowVO.setCustomerNo(customerNo);
        satCustomerFollowVO.setFollowStatus(followStatus);
        satCustomerFollowVO.setPartnerCode(loginInfo.getPartnerCode());
        List<SatCustomerFollowVO> list = satCustomerFollowService.getFollowsByNo(satCustomerFollowVO);
        return list;
    }

    /**
     * 订单创建完成即生成一条已跟进记录,跟进项为定金订单
     * 变更客户级别为O级
     * 生成一条待交车记录
     * @param orderCustomerId
     * @param planHandleVehicleTime 预计交车时间
     * @throws Exception
     */
    @Override
    public void orderCustomerFollow(String orderCustomerId,Date planHandleVehicleTime,boolean isCreateOrder,boolean isNewHandleVehicleInfo,LoginInfo loginInfo) throws Exception {
        if(StringUtil.isNotEmpty(orderCustomerId)){
            OrderCustomer orderCustomer = orderCustomerService.getById(orderCustomerId);
            if(orderCustomer != null){
                if (isCreateOrder){
                    SatCustomerFollow satCustomerFollow = new SatCustomerFollow();
                    satCustomerFollow.setCustomerNo(orderCustomer.getCustomerNo());
                    satCustomerFollow.setPartnerCode(orderCustomer.getPartnerCode());
                    satCustomerFollow.setFollowItem("3");//根跟进事项定金订单
                    SatCustomerFollowVO satCustomerFollowVO1 = new SatCustomerFollowVO();
                    satCustomerFollowVO1.setCustomerNo(orderCustomer.getCustomerNo());
                    satCustomerFollowVO1.setPartnerCode(orderCustomer.getPartnerCode());
                    String level = satCustomerFollowService.getCustomerLevelByNo(satCustomerFollowVO1);
                    satCustomerFollow.setLevel(level);//跟进前客户级别
                    satCustomerFollow.setNewCustlevel("1");//创建订单后客户级别变成O
                    satCustomerFollow.setPlanFollowTime(new Date());
                    satCustomerFollow.setCompleteFollowTime(new Date());
                    satCustomerFollow.setFollowStatus(1);//状态已完成
                    //1.新增跟进
                    satCustomerFollowService.saveOrUpdate(satCustomerFollow);
                    //2.变更客户级别为O级
                    SatCustomerFollowVO satCustomerFollowVO = new SatCustomerFollowVO();
                    satCustomerFollowVO.setCustomerNo(orderCustomer.getCustomerNo());
                    satCustomerFollowVO.setNewCustlevel("1");
                    satCustomerFollowVO.setPartnerCode(orderCustomer.getPartnerCode());
                    satCustomerFollowService.updateCustomerLevel(satCustomerFollowVO);
                }
                //3.生成一条待交车记录
                if (isNewHandleVehicleInfo){
                    newHandleVehicleInfo(planHandleVehicleTime, orderCustomer,loginInfo);
                }
            }
            else{
                throw new Exception("操作失败,无法根据id:"+orderCustomerId+"找到对应订单记录!");
            }
        }
        else{
            throw new Exception("操作失败,id为空!");
        }
    }


    /**
     * 待跟进客户
     * @param satCustomerFollowVO
     * @param loginInfo
     * @return
     * @throws Exception
     */
    @Override
    public List<SatCustomerFollowVO> waitFollow(SatCustomerFollowVO satCustomerFollowVO, LoginInfo loginInfo) throws Exception {
        satCustomerFollowVO.setPartnerCode(loginInfo.getPartnerCode());
        String positionCode = getPositionCode(loginInfo);
        if(StringUtils.isNotEmpty(loginInfo.getRoleCode()) && DictConstant.USER_ROLE_SALES.equals(loginInfo.getRoleCode())){
            satCustomerFollowVO.setCreateBy(loginInfo.getUserCode());
        }
        return satCustomerFollowService.waitFollow(satCustomerFollowVO);
    }

    @Override
    public String getPositionCode(LoginInfo loginInfo) {
        String positionCode = null;
        if(loginInfo.getStaff() != null){
            StaffVO staffVO = JSONObject.parseObject(JSONObject.toJSONString(loginInfo.getStaff()), StaffVO.class);
            positionCode = staffVO.getPositionCode();
        }
        return positionCode;
    }

    /**
     * 查询每日待跟进数量
     * @param loginInfo
     * @return
     * @throws Exception
     */
    @Override
    public List<SatCustomerFollowCountVO> getWaitFollowCount(LoginInfo loginInfo) throws Exception {
        String roleCode = loginInfo.getRoleCode();
        SatCustomerFollowCountVO satCustomerFollowCountVO = new SatCustomerFollowCountVO();
        //角色代码为空,默认按销售顾问查
        if(StringUtils.isEmpty(roleCode) || roleCode.equals(DictConstant.USER_ROLE_SALES)){
            satCustomerFollowCountVO.setUserCode(loginInfo.getUserCode());
        }
        satCustomerFollowCountVO.setPartnerCode(loginInfo.getPartnerCode());
        return satCustomerFollowService.getWaitFollowCount(satCustomerFollowCountVO);
    }

    @Override
    public PageInfo<SatCustomerFollowVO> waitFollowForPage(SatCustomerFollowVO satCustomerFollowVO, LoginInfo loginInfo, Integer pageNum, Integer pageSize) throws Exception {
        satCustomerFollowVO.setPartnerCode(loginInfo.getPartnerCode());
        String positionCode = getPositionCode(loginInfo);
        if(StringUtils.isNotEmpty(loginInfo.getRoleCode()) && DictConstant.USER_ROLE_SALES.equals(loginInfo.getRoleCode())){
            satCustomerFollowVO.setCreateBy(loginInfo.getUserCode());
        }
        return satCustomerFollowService.waitFollowForPage(satCustomerFollowVO,pageNum,pageSize);
    }

    /**
     * 逾期跟进客户
     * @param satCustomerFollowVO
     * @param loginInfo
     * @return
     * @throws Exception
     */
    @Override
    public List<SatCustomerFollowVO> lateFollow(SatCustomerFollowVO satCustomerFollowVO, LoginInfo loginInfo) throws Exception {
        satCustomerFollowVO.setPartnerCode(loginInfo.getPartnerCode());
        String positionCode = getPositionCode(loginInfo);
        if(StringUtils.isNotEmpty(loginInfo.getRoleCode()) && DictConstant.USER_ROLE_SALES.equals(loginInfo.getRoleCode())){
            satCustomerFollowVO.setCreateBy(loginInfo.getUserCode());
        }
        return satCustomerFollowService.lateFollow(satCustomerFollowVO);
    }

    @Override
    public PageInfo<SatCustomerFollowVO> lateFollowForPage(SatCustomerFollowVO satCustomerFollowVO, LoginInfo loginInfo, Integer pageNum, Integer pageSize) throws Exception {
        satCustomerFollowVO.setPartnerCode(loginInfo.getPartnerCode());
        String positionCode = getPositionCode(loginInfo);
        if(StringUtils.isNotEmpty(loginInfo.getRoleCode()) && DictConstant.USER_ROLE_SALES.equals(loginInfo.getRoleCode())){
            satCustomerFollowVO.setCreateBy(loginInfo.getUserCode());
        }
        return satCustomerFollowService.lateFollowForPage(satCustomerFollowVO,pageNum,pageSize);
    }

    /**
     * 老客户跟进
     * @param satCustomerFollowVO
     * @param loginInfo
     * @return
     * @throws Exception
     */
    @Override
    public List<SatCustomerFollowVO> goodCustomerFollow(SatCustomerFollowVO satCustomerFollowVO, LoginInfo loginInfo) throws Exception {
        satCustomerFollowVO.setPartnerCode(loginInfo.getPartnerCode());
        String positionCode = getPositionCode(loginInfo);
        if(StringUtils.isNotEmpty(loginInfo.getRoleCode()) && DictConstant.USER_ROLE_SALES.equals(loginInfo.getRoleCode())){
            satCustomerFollowVO.setCreateBy(loginInfo.getUserCode());
        }
        return satCustomerFollowService.goodCustomerFollow(satCustomerFollowVO);
    }

    @Override
    public PageInfo<SatCustomerFollowVO> goodCustomerFollowForPage(SatCustomerFollowVO satCustomerFollowVO, LoginInfo loginInfo, Integer pageNum, Integer pageSize) throws Exception {
        satCustomerFollowVO.setPartnerCode(loginInfo.getPartnerCode());
        String positionCode = getPositionCode(loginInfo);
        if(StringUtils.isNotEmpty(loginInfo.getRoleCode()) && DictConstant.USER_ROLE_SALES.equals(loginInfo.getRoleCode())){
            satCustomerFollowVO.setCreateBy(loginInfo.getUserCode());
        }
        return satCustomerFollowService.goodCustomerFollowForPage(satCustomerFollowVO,pageNum,pageSize);
    }

    /**
     * 今日跟进提醒报表
     * @param loginInfo
     * @return
     * @throws Exception
     */
    @Override
    public FollowRemindVO followRemind(LoginInfo loginInfo) throws Exception {
        FollowRemindVO followRemindVO = new FollowRemindVO();
        followRemindVO.setSalesConsultantNo(loginInfo.getUserCode());
        followRemindVO.setPartnerCode(loginInfo.getPartnerCode());
        Object staff = loginInfo.getStaff();
        String positionCode = null;
        if(staff != null){
            StaffVO staffVO = JSONObject.parseObject(JSONObject.toJSONString(staff), StaffVO.class);
            positionCode = staffVO.getPositionCode();
        }
        //销售经理、总经理查看全店
        if (StringUtils.isNotEmpty(loginInfo.getRoleCode()) && (
            DictConstant.USER_ROLE_MANAGER.equals(loginInfo.getRoleCode()) || DictConstant.USER_ROLE_PARTNER_MANAGER
                .equals(loginInfo.getRoleCode()))) {
            return satCustomerFollowService.manageFollowRemind(followRemindVO);
        }
        //其余角色查自己名下
        return satCustomerFollowService.followRemind(followRemindVO);
    }

    /**
     * 填充 PARTNER_CODE
     */
    private void setPartnerCode(SatCustomerFollowVO satCustomerFollowVO, LoginInfo loginInfo) throws IllegalAccessException, InvocationTargetException {
        Object partner = loginInfo.getPartner();
        if(partner != null){
            PartnerVO partnerVO = new PartnerVO();
            org.apache.commons.beanutils.BeanUtils.copyProperties(partnerVO,partner);
            satCustomerFollowVO.setPartnerCode(partnerVO.getPartnerCode());
        }
    }

    /**
     * 校验下次跟进日期是否匹配级别限定天数
     * 为空则填充
     * @param satCustomerFollow
     * @throws Exception
     */
    private void checkPlanFollowDate(SatCustomerFollow satCustomerFollow) throws Exception {
        Date planFollowTime = satCustomerFollow.getPlanFollowTime();
        String customerNo = satCustomerFollow.getCustomerNo();
        Integer limitDays = null;
        SatCustomerFollowVO satCustomerFollowVO = new SatCustomerFollowVO();
        satCustomerFollowVO.setCustomerNo(customerNo);
        satCustomerFollowVO.setPartnerCode(satCustomerFollow.getPartnerCode());
//        String level = satCustomerFollowService.getCustomerLevelByNo(satCustomerFollowVO);
        String level = satCustomerFollowVO.getNewCustlevel();
        if(StringUtil.isNotEmpty(level)){
            QueryWrapper<SatConfig> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("PARTNER_CODE",satCustomerFollow.getPartnerCode());
            SatConfig satConfig = satConfigService.getOne(queryWrapper);
            if(satConfig != null){
                switch (level){
                    case "1":
                        limitDays = satConfig.getCustomerOFollowDays();
                        break;
                    case "2":
                        limitDays = satConfig.getCustomerHFollowDays();
                        break;
                    case "3":
                        limitDays = satConfig.getCustomerAFollowDays();
                        break;
                    case "4":
                        limitDays = satConfig.getCustomerBFollowDays();
                        break;
                    case "5":
                        limitDays = satConfig.getCustomerCFollowDays();
                        break;
                    case "6":
                        limitDays = satConfig.getCustomerOtherFollowDays();
                        break;
                }
            }
        }
        if(planFollowTime != null && limitDays != null){
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String planFollowTimeStr = simpleDateFormat.format(planFollowTime);
            planFollowTime = simpleDateFormat.parse(simpleDateFormat.format(planFollowTime));
            Date nowDate = new Date();
            String nowDateStr = simpleDateFormat.format(nowDate);
            nowDate = simpleDateFormat.parse(simpleDateFormat.format(nowDate));
            int i = planFollowTime.compareTo(nowDate);//1大于,0等于,-1小于
            if(i<0){
                throw new Exception("操作失败,计划跟进日期"+planFollowTimeStr+"不能小于当前日期"+nowDateStr+"!");
            }
            Calendar c1 = Calendar.getInstance();
            Calendar c2 = Calendar.getInstance();
            c1.setTime(planFollowTime);
            c2.setTime(nowDate);
            Long intervalDays = (c1.getTime().getTime()-c2.getTime().getTime())/1000/60/60/24;//间隔天数
            c2.add(Calendar.DATE,limitDays);
            Date time = c2.getTime();
            String format = simpleDateFormat.format(time);
            if(intervalDays>limitDays){
                throw new Exception("操作失败,计划跟进日期:"+planFollowTimeStr+"不能超过"+format+"!");
            }

        }
        if(planFollowTime == null && limitDays != null){
            Calendar instance = Calendar.getInstance();
            instance.add(Calendar.DATE,limitDays);
            Date time = instance.getTime();
            satCustomerFollow.setPlanFollowTime(time);
        }
        else if(planFollowTime == null && limitDays == null){
            satCustomerFollow.setPlanFollowTime(new Date());
        }
    }

    /**
     * 新增交车记录
     * @param planHandleVehicleTime
     * @param orderCustomer
     */
    private void newHandleVehicleInfo(Date planHandleVehicleTime, OrderCustomer orderCustomer,LoginInfo loginInfo) {
        HandleVehicle handleVehicle = new HandleVehicle();
        handleVehicle.setPartnerCode(orderCustomer.getPartnerCode());
        handleVehicle.setOrderCustomerNo(orderCustomer.getOrderCustomerNo());
        handleVehicle.setSalesConsultantNo(loginInfo.getUserCode());
        handleVehicle.setCustomerNo(orderCustomer.getCustomerNo());
        handleVehicle.setHandleTime(planHandleVehicleTime);
        handleVehicle.setHandleUser(orderCustomer.getHandleUser());
        handleVehicle.setHandleStatus(1);
        HandleVehicleVO hv = new HandleVehicleVO();
        hv.setOrderCustomerNo(orderCustomer.getOrderCustomerNo());
        List<HandleVehicleVO> list = handleVehicleService.listByVo(hv);
        if (list!=null && list.size()>0){
            handleVehicle.setHandleId(list.get(0).getHandleId());
        }
        handleVehicleService.saveOrUpdate(handleVehicle);
    }


    /**
     * 生成消息
     * @param satCustomerFollow
     * @param roleCode
     */
    private void pushMsg(SatCustomerFollow satCustomerFollow, String roleCode,String applyId) throws InvocationTargetException, IllegalAccessException {
        LoginInfo loginInfo = new LoginInfo();
        loginInfo.setPartnerCode(satCustomerFollow.getPartnerCode());
        ApiResult rolePartnerSaleManager = staffDubboService.listStaffByRoleCode("rolePartnerSaleManager", loginInfo);
        if(rolePartnerSaleManager != null){
            List<StaffVO> data = (List<StaffVO>)rolePartnerSaleManager.getData();
            if(data != null && data.size() > 0){
                SatCustomerClueVO satCustomerClueVO = new SatCustomerClueVO();
                satCustomerClueVO.setCustomerNo(satCustomerFollow.getCustomerNo());
                satCustomerClueVO.setPartnerCode(satCustomerFollow.getPartnerCode());
                String customerName = satCustomerClueService.getCustomerNameByNo(satCustomerClueVO);
                for (StaffVO vo : data){
                    SatMessAddVO satMessAddVO = new SatMessAddVO();
                    satMessAddVO.setType("4");
                    satMessAddVO.setTemplateType(11);
                    satMessAddVO.setCustomerName(customerName);
                    satMessAddVO.setCustomerNo(satCustomerFollow.getCustomerNo());
                    satMessAddVO.setSalesConsultantNo(vo.getAccountNo());
                    satMessAddVO.setReceiveRoleCode("rolePartnerSaleManager");
                    satMessAddVO.setOperaRoleCode(roleCode);
                    satMessAddVO.setBusinessKey(applyId);
                    satMessService.newMess(satMessAddVO);
                }
            }
        }
    }
}
